﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tunnel.Entity;

namespace Tunnel.Tools.FcmsTools
{
    public partial class FcmsForm : Form
    {
        /// <summary>
        /// 情报板设备ID
        /// </summary>
        string fcmsId;

        /// <summary>
        /// 当前编辑的播放列表ID
        /// </summary>
        string playListId;

        /// <summary>
        /// 当前选择的情报板的发送命令的变量名
        /// </summary>
        public string selectFcmsParamName;
        /// <summary>
        /// 当前选择的情报板的ControlSwitch的变量名
        /// </summary>
        string controlSwitch;
        /// <summary>
        /// 用以记录播放列表内容的DataTable
        /// </summary>
        DataTable dtPlayListInfo;
        /// <summary>
        /// 每一屏幕的内容对象
        /// </summary>
        DisplayElement element = new DisplayElement();
        /// <summary>
        /// 情报板协议对象
        /// </summary>
        FcmsProtocol fcmsProtocol = new FcmsProtocol();
        /// <summary>
        /// 模拟字体大小，等于FontSize*屏幕缩放系数
        /// </summary>
        int simulationFontSize;
        /// <summary>
        /// 屏幕缩放系数
        /// </summary>
        private int zoomCoefficient = 2;
        /// <summary>
        /// 模拟字体
        /// </summary>
        private string simulationFont = "宋体";
        /// <summary>
        /// 用以记录播放列表LIST的DataTable
        /// </summary>
        DataTable dtGetPlayList = new DataTable();
        /// <summary>
        /// 用以记录情报板LIST的DataTable
        /// </summary>
        DataTable dtGetFcmss = new DataTable();
        List<string> savelog = new List<string>();
        /// <summary>
        /// 情报板的高度
        /// </summary>
        int screenHeight = 96;
        /// <summary>
        /// 情报板的宽度
        /// </summary>
        int screenWidth = 128;

        /// <summary>
        /// 窗体打开时传递的FCMS的设备ID
        /// </summary>
        string deviceId;

        public FcmsForm()
        {
            InitializeComponent();            
        }

        public FcmsForm(string deviceId)
        {
            InitializeComponent();
            this.deviceId = deviceId;
        }

       
        /// <summary>
        /// 刷新预览窗体的显示内容
        /// </summary>
        public void RefreshFCMS()
        {
            if (dgvPlayList.SelectedRows.Count != 0)
            {
                try
                {
                    int rowIndex = this.dgvPlayList.SelectedCells[0].RowIndex;
                    DisplayElement element = new DisplayElement();
                    element.Msg = this.dgvPlayList.Rows[rowIndex].Cells["显示内容"].Value.ToString();
                    element.MsgX = this.dgvPlayList.Rows[rowIndex].Cells["坐标X"].Value.ToString();
                    element.MsgY = this.dgvPlayList.Rows[rowIndex].Cells["坐标Y"].Value.ToString();
                    element.Delay = this.dgvPlayList.Rows[rowIndex].Cells["停留时间"].Value.ToString();
                    element.FontSize = this.dgvPlayList.Rows[rowIndex].Cells["字号"].Value.ToString();
                    element.Colour = this.dgvPlayList.Rows[rowIndex].Cells["字体颜色"].Value.ToString();

                    this.lableTextPrewiew.Location = new Point(0, 0);

                    switch (element.Colour)
                    {
                        case "红色":
                            this.lableTextPrewiew.ForeColor = Color.Red;
                            break;

                        case "绿色":
                            this.lableTextPrewiew.ForeColor = Color.LawnGreen;
                            break;

                        case "蓝色":
                            this.lableTextPrewiew.ForeColor = Color.DeepSkyBlue;
                            break;

                        case "黄色":
                            this.lableTextPrewiew.ForeColor = Color.Yellow;
                            break;
                    }

                    this.simulationFontSize = int.Parse(element.FontSize) * this.zoomCoefficient;


                    this.lableTextPrewiew.Font = new Font(this.simulationFont, (float)this.simulationFontSize, GraphicsUnit.Pixel);


                    int index = element.Msg.IndexOf(@"\n");
                    if (index == -1)
                    {
                        this.lableTextPrewiew.Text = element.Msg;
                    }
                    else
                    {
                        string msg = element.Msg;

                        lableTextPrewiew.Text = msg.Replace(@"\n", "\r\n");
                    }
                    this.lableTextPrewiew.Location = new Point((int)((this.panelUp.Width - this.lableTextPrewiew.Width) / 2), (int)((this.panelUp.Height - this.lableTextPrewiew.Height) / 2));
                }
                catch { }

            }

        }
        /// <summary>
        /// 即将对dgvPlayList的单元格内容进行编辑，解除编辑事件绑定
        /// </summary>
        private void BeginEditGridValue()
        {
            try
            {
                dgvPlayList.CellValueChanged -= dgvPlayList_CellValueChanged;
            }
            catch { }
        }
        /// <summary>
        /// 完成对dgvPlayList的单元格内容进行编辑，恢复编辑事件绑定
        /// </summary>
        private void EndEditGridValue()
        {
            try
            {
                dgvPlayList.CellValueChanged += dgvPlayList_CellValueChanged;
            }
            catch { }            
        }

        /// <summary>
        /// 分屏之后增加\n等内容
        /// </summary>
        /// <param name="dataGridViewRowIndex">要操作的屏幕所在的DataGridView的行数</param>
        private void AutoDealMessage(int dataGridViewRowIndex)
        {
            if (dataGridViewRowIndex > -1 && dgvPlayList.Rows[dataGridViewRowIndex].Cells["字号"].Value != null && dgvPlayList.Rows[dataGridViewRowIndex].Cells["显示内容"].Value != null && dgvPlayList.Rows[dataGridViewRowIndex].Cells["字号"].Value != null && dgvPlayList.Rows[dataGridViewRowIndex].Cells["字体颜色"].Value != null)
            {
                string text1 = dgvPlayList.Rows[dataGridViewRowIndex].Cells["显示内容"].Value.ToString();
                int fontSize = int.Parse(dgvPlayList.Rows[dataGridViewRowIndex].Cells["字号"].Value.ToString());
                FcmsUtilities.AutoSplitScreen(ref text1, out string text2, fontSize, screenWidth, screenHeight);
                BeginEditGridValue();
                dgvPlayList.Rows[dataGridViewRowIndex].Cells["显示内容"].Value = text1;
                EndEditGridValue();
                if (!string.IsNullOrEmpty(text2))
                {
                    BeginEditGridValue();
                    dgvPlayList.Rows.Insert(dataGridViewRowIndex + 1, new object[] { text2, dgvPlayList.Rows[dataGridViewRowIndex].Cells["停留时间"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["字号"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["字体颜色"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["坐标X"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["坐标Y"].Value.ToString() });
                    EndEditGridValue();
                }
                BeginEditGridValue();
                dgvPlayList.Rows[dataGridViewRowIndex].Cells["坐标X"].Value = (screenWidth - (FcmsUtilities.MaxLineLength(text1) * fontSize / 2)) / 2;
                dgvPlayList.Rows[dataGridViewRowIndex].Cells["坐标Y"].Value = (screenHeight - (fontSize * FcmsUtilities.GetLinesCount(text1))) / 2;
                EndEditGridValue();
                this.lableTextPrewiew.Location = new Point((int)((this.panelUp.Width - this.lableTextPrewiew.Width) / 2), (int)((this.panelUp.Height - this.lableTextPrewiew.Height) / 2));
                RefreshFCMS();
            }

        }
        #region 废弃代码
        /// <summary>
        /// 分屏之后增加\n等内容
        /// </summary>
        /// <param name="dataGridViewRowIndex">要操作的屏幕所在的DataGridView的行数</param>
        //private void AutoDealMessage3(int dataGridViewRowIndex)
        //{
        //    if (dataGridViewRowIndex > -1 && dgvPlayList.Rows[dataGridViewRowIndex].Cells["字号"].Value != null && dgvPlayList.Rows[dataGridViewRowIndex].Cells["显示内容"].Value != null && dgvPlayList.Rows[dataGridViewRowIndex].Cells["字号"].Value != null && dgvPlayList.Rows[dataGridViewRowIndex].Cells["字体颜色"].Value != null)
        //    {
        //        DataGridViewTextBoxCell textboxCell = (DataGridViewTextBoxCell)dgvPlayList.Rows[dataGridViewRowIndex].Cells["显示内容"];
        //        DataGridViewComboBoxCell comboxCell = (DataGridViewComboBoxCell)dgvPlayList.Rows[dataGridViewRowIndex].Cells["字号"];

        //        string text1 = textboxCell.Value.ToString();//.Replace(@"\n", string.Empty); 
        //        FcmsUtilities.AutoSplitScreen3(ref text1, out string text2, Convert.ToInt32(comboxCell.Value.ToString()), screenWidth, screenHeight);
        //        if (!string.IsNullOrEmpty(text2))
        //        {
        //            dgvPlayList.CellValueChanged -= dgvPlayList_CellValueChanged;
        //            textboxCell.Value = FcmsUtilities.InsertEnterIntoString(text1, Convert.ToInt32(comboxCell.Value.ToString()), screenWidth, screenHeight);
        //            dgvPlayList.Rows.Insert(dataGridViewRowIndex + 1, new object[] { text2, dgvPlayList.Rows[dataGridViewRowIndex].Cells["停留时间"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["字号"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["字体颜色"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["坐标X"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["坐标Y"].Value.ToString() });
        //            dgvPlayList.CellValueChanged += dgvPlayList_CellValueChanged;
        //        }
        //        else
        //        {
        //            dgvPlayList.CellValueChanged -= dgvPlayList_CellValueChanged;
        //            textboxCell.Value = FcmsUtilities.InsertEnterIntoString(text1, Convert.ToInt32(comboxCell.Value.ToString()), screenWidth, screenHeight);
        //            dgvPlayList.CellValueChanged += dgvPlayList_CellValueChanged;
        //        }

        //        DataGridViewTextBoxCell textboxCellX = (DataGridViewTextBoxCell)dgvPlayList.Rows[dataGridViewRowIndex].Cells["坐标X"];
        //        DataGridViewTextBoxCell textboxCellY = (DataGridViewTextBoxCell)dgvPlayList.Rows[dataGridViewRowIndex].Cells["坐标Y"];
        //        int fontsize = int.Parse(comboxCell.Value.ToString());
        //        RefreshFCMS();//将新的字符串刷入预览LABEL，之后按照新的字符串计算位置
        //        dgvPlayList.CellValueChanged -= dgvPlayList_CellValueChanged;
        //        textboxCellX.Value = (screenWidth - ((fontsize / 2) * FcmsUtilities.MaxLineLength(textboxCell.Value.ToString()))) / 2;
        //        textboxCellY.Value = (64 - (fontsize * FcmsUtilities.GetLinesCount(textboxCell.Value.ToString()))) / 2;
        //        dgvPlayList.CellValueChanged += dgvPlayList_CellValueChanged;
        //        this.lableTextPrewiew.Location = new Point((int)((this.panelUp.Width - this.lableTextPrewiew.Width) / 2), (int)((this.panelUp.Height - this.lableTextPrewiew.Height) / 2));
        //        RefreshFCMS();
        //        #region 无用代码
        //        //int max = FcmsUtilities.GetMaxSbcTextCountInScreen(Convert.ToInt32(comboxCell.Value.ToString()), screenWidth, screenHeight);
        //        //string noEnterString = textboxCell.Value?.ToString().Replace(@"\n", string.Empty);
        //        //if (textboxCell.Value != null && Encoding.Default.GetByteCount(noEnterString) > max)
        //        //{
        //        //    string lastChar = Encoding.Default.GetString(Encoding.Default.GetBytes(noEnterString), 0, max).Substring(Encoding.Default.GetString(Encoding.Default.GetBytes(noEnterString), 0, max).Length - 1, 1);
        //        //    if (lastChar != "?") //判断半角字符数量是否为偶数个
        //        //    {
        //        //        string text1 = Encoding.Default.GetString(Encoding.Default.GetBytes(noEnterString), 0, max);
        //        //        string text2 = Encoding.Default.GetString(Encoding.Default.GetBytes(noEnterString), max, Encoding.Default.GetByteCount(noEnterString) - max);
        //        //        dgvPlayList.CellValueChanged -= dgvPlayList_CellValueChanged;
        //        //        //textboxCell.Value = insertEnterIntoString(text1, comboxCell.Value.ToString());//将本屏幕内剩余的字符串添加回车符
        //        //        textboxCell.Value = FcmsUtilities.InsertEnterIntoString(text1, Convert.ToInt32(comboxCell.Value.ToString()), 128, 64);
        //        //        dgvPlayList.Rows.Insert(dataGridViewRowIndex + 1, new object[] { text2, dgvPlayList.Rows[dataGridViewRowIndex].Cells["停留时间"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["字号"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["字体颜色"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["坐标X"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["坐标Y"].Value.ToString() });
        //        //        dgvPlayList.CellValueChanged += dgvPlayList_CellValueChanged;

        //        //    }
        //        //    else //如果是奇数个，则需要往前提前半个全角字符截取
        //        //    {
        //        //        string text1 = Encoding.Default.GetString(Encoding.Default.GetBytes(noEnterString), 0, max - 1);
        //        //        string text2 = Encoding.Default.GetString(Encoding.Default.GetBytes(noEnterString), max - 1, Encoding.Default.GetByteCount(noEnterString) - max + 1);
        //        //        dgvPlayList.CellValueChanged -= dgvPlayList_CellValueChanged;
        //        //        //textboxCell.Value = insertEnterIntoString(text1, comboxCell.Value.ToString());//将本屏幕内剩余的字符串添加回车符
        //        //        textboxCell.Value = FcmsUtilities.InsertEnterIntoString(text1, Convert.ToInt32(comboxCell.Value.ToString()), screenWidth, screenHeight);
        //        //        dgvPlayList.Rows.Insert(dataGridViewRowIndex + 1, new object[] { text2, dgvPlayList.Rows[dataGridViewRowIndex].Cells["停留时间"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["字号"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["字体颜色"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["坐标X"].Value.ToString(), dgvPlayList.Rows[dataGridViewRowIndex].Cells["坐标Y"].Value.ToString() });
        //        //        dgvPlayList.CellValueChanged += dgvPlayList_CellValueChanged;
        //        //    }
        //        //}
        //        //if (Encoding.Default.GetByteCount(noEnterString) <= max)
        //        //{
        //        //    //textboxCell.Value = insertEnterIntoString(noEnterString, comboxCell.Value.ToString());
        //        //    textboxCell.Value = FcmsUtilities.InsertEnterIntoString(noEnterString, Convert.ToInt32(comboxCell.Value.ToString()), screenWidth, screenHeight);
        //        //}
        //        //DataGridViewTextBoxCell textboxCellX = (DataGridViewTextBoxCell)dgvPlayList.Rows[dataGridViewRowIndex].Cells["坐标X"];
        //        //DataGridViewTextBoxCell textboxCellY = (DataGridViewTextBoxCell)dgvPlayList.Rows[dataGridViewRowIndex].Cells["坐标Y"];
        //        //int fontsize = int.Parse(comboxCell.Value.ToString());
        //        //RefreshFCMS();//将新的字符串刷入预览LABEL，之后按照新的字符串计算位置
        //        //textboxCellX.Value = (screenWidth - ((fontsize / 2) * FcmsUtilities.MaxLineLength(textboxCell.Value.ToString()))) / 2;
        //        //textboxCellY.Value = (screenHeight - (fontsize * FcmsUtilities.GetLinesCount(textboxCell.Value.ToString()))) / 2;
        //        //this.lableTextPrewiew.Location = new Point((int)((this.panelUp.Width - this.lableTextPrewiew.Width) / 2), (int)((this.panelUp.Height - this.lableTextPrewiew.Height) / 2));
        //        //RefreshFCMS();
        //        #endregion
        //    }
        //}
        #endregion
        /// <summary>
        /// 获取情报板的相关信息，包括对应的播放列表，使用的PLC，情报板ID和PLC的相关变量名
        /// </summary>
        public async Task GetFcmss()
        {
            var sdh = new DBHelper();
            string sqlGetFcmss = "SELECT M_Device.DeviceID+'$'+R_FcmsStatus.ParamName+'$'+R_FcmsStatus.PlayListID+'$'+R_FcmsStatus.ControlSwitch+'$'+M_Device.Protocol as IDandPARAM, M_Device.Name, R_FcmsStatus.ParamName FROM M_Device LEFT OUTER JOIN R_FcmsStatus ON M_Device.DeviceID = R_FcmsStatus.FCMSID WHERE (M_Device.TypeID = 'FCMS')";
            dtGetFcmss = await sdh.GetTableAsync(sqlGetFcmss);
            cbFcmss.DataSource = dtGetFcmss;
        }
             
        /// <summary>
        /// 填写播放列表下拉列表
        /// </summary>
        public async Task GetPlayList()
        {
            var sdh = new DBHelper();
            string sqlGetPlayList = "SELECT [PlayListID],[Name],[UsingFCMS] FROM [M_PlayList]";
            dtGetPlayList = await sdh.GetTableAsync(sqlGetPlayList);
            cbPlayList.DataSource = dtGetPlayList;
        }
        /// <summary>
        /// 将播放列表的信息逐个写入DataGridView
        /// </summary>
        private async void FillTheGridView()
        {
            BeginEditGridValue();
            dgvPlayList.Rows.Clear();
            if (string.IsNullOrEmpty(playListId))
            {
                return;
            }
            string sqlFillGridView = $"SELECT Text, StayTime, FontSize, FontColor,TextX,TextY,Number FROM M_PlayListInfo WHERE PlayListID = '{ playListId }' ORDER BY Number";
            var sdh = new DBHelper();
            dtPlayListInfo = await sdh.GetTableAsync(sqlFillGridView);
            dgvPlayList.Rows.Clear();
            foreach (DataRow dr in dtPlayListInfo.Rows)
            {
                dgvPlayList.Rows.Add(1);

                DataGridViewRow lastDr = dgvPlayList.Rows[dgvPlayList.RowCount - 1];
                lastDr.Cells["显示内容"].Value = dr["Text"].ToString();
                lastDr.Cells["停留时间"].Value = dr["StayTime"].ToString();
                lastDr.Cells["字号"].Value = dr["FontSize"].ToString();
                lastDr.Cells["字体颜色"].Value = dr["FontColor"].ToString();
                lastDr.Cells["坐标X"].Value = dr["TextX"].ToString();
                lastDr.Cells["坐标Y"].Value = dr["TextY"].ToString();
            }
            EndEditGridValue();
            if(dgvPlayList.Rows.Count>0)
            {
                dgvPlayList.Rows[0].Selected = true;
                RefreshFCMS();
            }
        }
        /// <summary>
        /// 表格右键点击方法，用来弹出右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvPlayList_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    //若行已是选中状态就不再进行设置
                    if (dgvPlayList.Rows[e.RowIndex].Selected == false)
                    {
                        dgvPlayList.ClearSelection();
                        dgvPlayList.Rows[e.RowIndex].Selected = true;
                    }
                    //只选中一行时设置活动单元格
                    //if (dgvPlayList.SelectedRows.Count == 1)
                    //{
                    //    dgvPlayList.CurrentCell = dgvPlayList.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    //}
                    //弹出操作菜单
                    cmsDGV.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }
        /// <summary>
        /// 表格每一行绘制后运行的方法，用以添加表头的第X行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvPlayList_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            using (SolidBrush b = new SolidBrush(dgvPlayList.RowHeadersDefaultCellStyle.ForeColor))
            {
                e.Graphics.DrawString("第" + (e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture) + "屏", e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
            }
        }
        /// <summary>
        /// 上移按钮事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rowUp_Click(object sender, EventArgs e)
        {
            int rowIndex = dgvPlayList.SelectedRows[0].Index;  //得到当前选中行的索引     

            if (rowIndex == 0)
            {
                MessageBox.Show("已经是第一行了!");
                return;
            }

            List<string> list = new List<string>();
            
            foreach(DataGridViewCell item in dgvPlayList.SelectedRows[0].Cells)
            {
                if(item.Value!=null)
                {
                    list.Add(item.Value.ToString());
                }
                else
                {
                    list.Add(string.Empty);
                }
            }
            dgvPlayList.Rows[rowIndex].Selected = false;
            dgvPlayList.CellValueChanged -= dgvPlayList_CellValueChanged;
            for (int j = 0; j < dgvPlayList.Columns.Count; j++)
            {
                dgvPlayList.Rows[rowIndex].Cells[j].Value = dgvPlayList.Rows[rowIndex - 1].Cells[j].Value;
                dgvPlayList.Rows[rowIndex - 1].Cells[j].Value = list[j].ToString();
            }
            dgvPlayList.Rows[rowIndex - 1].Selected = true;
            dgvPlayList.CellValueChanged += dgvPlayList_CellValueChanged;

            RefreshFCMS();
        }
        /// <summary>
        /// 下移按钮事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rowDown_Click(object sender, EventArgs e)
        {
            int rowIndex = dgvPlayList.SelectedRows[0].Index;  //得到当前选中行的索引     

            if (rowIndex == dgvPlayList.Rows.Count - 1)
            {
                MessageBox.Show("已经是最后一行了!");
                return;
            }

            List<string> list = new List<string>();
            foreach (DataGridViewCell item in dgvPlayList.SelectedRows[0].Cells)
            {
                if (item.Value != null)
                {
                    list.Add(item.Value.ToString());
                }
                else
                {
                    list.Add(string.Empty);
                }
            }
            dgvPlayList.Rows[rowIndex].Selected = false;
            dgvPlayList.CellValueChanged -= dgvPlayList_CellValueChanged;
            for (int j = 0; j < dgvPlayList.Columns.Count; j++)
            {
                dgvPlayList.Rows[rowIndex].Cells[j].Value = dgvPlayList.Rows[rowIndex + 1].Cells[j].Value;
                dgvPlayList.Rows[rowIndex + 1].Cells[j].Value = list[j].ToString();
            }
            dgvPlayList.Rows[rowIndex + 1].Selected = true;
            dgvPlayList.CellValueChanged += dgvPlayList_CellValueChanged;
            RefreshFCMS();
        }
        /// <summary>
        /// 增加按钮事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rowInsert_Click(object sender, EventArgs e)
        {
            dgvPlayList.Rows.Add(new object[] { string.Empty, "1", "24", "绿色", "0", "0" });
            dgvPlayList.Rows[dgvPlayList.Rows.Count - 1].Selected = true;
        }
        /// <summary>
        /// 删除按钮事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rowDelete_Click(object sender, EventArgs e)
        {
            dgvPlayList.Rows.Remove(dgvPlayList.SelectedRows[0]);
        }
        /// <summary>
        /// 保存按钮事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void listSave_Click(object sender, EventArgs e)
        {
            int number = 1;
            List<string> lslist = new List<string>();
            string sqlClear = $"delete from M_PlayListInfo where PlayListID='{ playListId }'";
            lslist.Add(sqlClear);
            foreach (DataGridViewRow dgvr in dgvPlayList.Rows)
            {
                if (!string.IsNullOrEmpty(dgvr.Cells["显示内容"].Value.ToString()))
                {

                    string sqlInfoInsert = "INSERT INTO M_PlayListInfo(PlayID,PlayListID,Text,StayTime,FontSize,FontColor,TextX,TextY,Number) VALUES ('" + DBHelper.GetGuid + "','" + playListId + "','" + dgvr.Cells["显示内容"].Value.ToString() + "','" + dgvr.Cells["停留时间"].Value.ToString() + "','" + dgvr.Cells["字号"].Value.ToString() + "','" + dgvr.Cells["字体颜色"].Value.ToString() + "','" + dgvr.Cells["坐标X"].Value.ToString() + "','" + dgvr.Cells["坐标Y"].Value.ToString() + "','" + number + "')";
                    number++;
                    lslist.Add(sqlInfoInsert);
                }
            }
            string[] sqlListSave = lslist.ToArray();
            var sdh = new DBHelper();
            int i = await sdh.RunTransactionCommandsAsync(sqlListSave);
            if (i != 0)
            {
                MessageBox.Show("已保存该播放列表，共" + (number - 1).ToString() + "条", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }        
        
        /// <summary>
        /// 发布按钮事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void publishList_Click(object sender, EventArgs e)
        {
            try
            {
                savelog.Clear();

                if (dgvPlayList.RowCount == 0)
                {
                    MessageBox.Show("播放列表为空，请先添加情报板内容", "播放列表为空", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    FcmsPlayList fcmsPlayList = new FcmsPlayList();
                    List<byte> file = new List<byte>();
                    fcmsPlayList.ClearItem();
                    foreach (DataGridViewRow dgvr in dgvPlayList.Rows)
                    {
                        DisplayElement element = new DisplayElement();
                        element.Msg = dgvr.Cells["显示内容"].Value.ToString();
                        element.MsgX = dgvr.Cells["坐标X"].Value.ToString();
                        element.MsgY = dgvr.Cells["坐标Y"].Value.ToString();
                        element.Delay = (int.Parse(dgvr.Cells["停留时间"].Value.ToString()) * 100).ToString();
                        element.FontSize = dgvr.Cells["字号"].Value.ToString() + dgvr.Cells["字号"].Value.ToString();
                        element.Colour = dgvr.Cells["字体颜色"].Value.ToString();
                        savelog.Add(element.ToString());
                        fcmsPlayList.AddItem(element);
                    }
                    file = fcmsPlayList.GetPlayList();
                    bool successed = false;
                    publishList.Enabled = false;
                    publishList.Text = "请稍候";
                    using (StreamWriter writer = new StreamWriter(Application.StartupPath + @"\\play.lst", false, Encoding.Default))
                    {
                        await writer.WriteAsync(Encoding.Default.GetString(file.ToArray()));
                        if (selectFcmsParamName.Contains("PLC"))
                        {
                            successed = fcmsProtocol.UploadFileBySql("play.lst", file, fcmsId, selectFcmsParamName, controlSwitch);
                        }
                        if (selectFcmsParamName.Contains("COM"))
                        {
                            successed = fcmsProtocol.UploadFileBySp("play.lst", file, fcmsId, selectFcmsParamName);
                        }
                        if (selectFcmsParamName.Contains("IP"))
                        {
                            string[] ipInfo = selectFcmsParamName.Split(':');
                            System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse(ipInfo[1]);
                            successed = fcmsProtocol.UploadFileByNet("play.lst", file, fcmsId, ipAddress, int.Parse(ipInfo[2]));
                        }
                    }
                    if (successed)
                    {
                        DBHelper sdh = new DBHelper();
                        string sql = $"UPDATE [R_FcmsStatus] SET [PlayListID]='{ playListId }' WHERE [FCMSID]='{ fcmsId }'";
                        string fcmstext = "";
                        foreach (var item in savelog)
                        {
                            fcmstext = fcmstext + " " + item;
                        }
                        string sql2 = $"insert into H_FCMSLog(FLogID,FCMSID,FCMSTEXT,UserID,UpdateTime) VALUES ('{ DBHelper.GetGuid }','{ fcmsId }','{ fcmstext }','{ Global.UserID }','{ DateTime.Now.ToString() }')";
                        await sdh.RunTransactionCommandsAsync(new string[] { sql, sql2 });
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.Append("发送内容:");
                        foreach(var item in savelog)
                        {
                            stringBuilder.Append(item);
                            stringBuilder.Append(" ");
                        }
                        
                        DataDeal.LogDB(fcmsId, "FCMS", stringBuilder.ToString());
                        MessageBox.Show("指令下发成功");
                        deviceId = fcmsId;
                        SelectFcmsAndPlaylist();
                    }
                    publishList.Text = "发布信息";
                    publishList.Enabled = true;

                }

            }
            catch { }
        }
        /// <summary>
        /// 当表格内容改变时的方法，用以自动分屏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvPlayList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            AutoDealMessage(e.RowIndex);

        }
        /// <summary>
        /// 表格内容增加时的方法，用以自动分屏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvPlayList_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            AutoDealMessage(e.RowIndex);

        }
        /// <summary>
        /// 表格选择行改变时的方法，用以刷新预览区域
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvPlayList_SelectionChanged(object sender, EventArgs e)
        {
            RefreshFCMS();
        }
        
        /// <summary>
        /// 情报板下拉选单的选择事件，此方法会修改当前的情报板ID、ControlSwitch和变量名等信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbFcmss_SelectedValueChanged(object sender, EventArgs e)
        {
            string[] idAndParam = cbFcmss.SelectedValue.ToString().Split('$');
            fcmsId = idAndParam[0];
            selectFcmsParamName = idAndParam[1];
            string fcmsPlaylistID = idAndParam[2];
            controlSwitch = idAndParam[3];
            string plc = idAndParam[4];
            //检查设备PLC是否处于可用状态

            if (fcmsPlaylistID != null)
            {
                cbPlayList.SelectedValue = fcmsPlaylistID;
            }
            else
            {
                cbPlayList.SelectedValue = null;
            }
            try
            {
                if (!Global.PlcStatus[plc])
                {
                    publishList.Enabled = false;
                    publishList.Text = "PLC异常";
                }
                else
                {
                    publishList.Enabled = true;
                    publishList.Text = "发布信息";
                }
            }
            catch
            {
                publishList.Enabled = true;
                publishList.Text = "发布信息";
            }
        }
        /// <summary>
        /// 播放列表下拉选单选项被修改时触发的方法，用以填充表格内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbPlayList_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                playListId = cbPlayList.SelectedValue.ToString();
            }
            catch
            {
                playListId = string.Empty;
            }
            FillTheGridView();
            
        }

        private async void deleteList_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确定删除这个播放列表及其全部内容吗？", "请确认", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                string sqlDeletePlayList = $"DELETE FROM M_PlayList WHERE PlayListID='{ cbPlayList.SelectedValue.ToString() }'";
                string sqlDeletePlayListInfo = $"DELETE FROM M_PlayListInfo WHERE PlayListID='{ cbPlayList.SelectedValue.ToString() }'";
                string[] sqlDeleteList = { sqlDeletePlayList, sqlDeletePlayListInfo };
                var sdh = new DBHelper();
                int count = await sdh.RunTransactionCommandsAsync(sqlDeleteList);
                if (count != 0)
                {
                    MessageBox.Show("删除成功！");
                }
                await GetPlayList();

            }
        }
        /// <summary>
        /// 新增播放列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void addList_Click(object sender, EventArgs e)
        {

            var sdh = new DBHelper();
            string sqlInsertPlayList = $"INSERT INTO M_PlayList (PlayListID,Name,usingFCMS) VALUES ('{ DBHelper.GetGuid }','{ cbPlayList.Text }','')";
            string newPlayListName = cbPlayList.Text;
            if (newPlayListName == string.Empty)
            {
                MessageBox.Show("请输入播放列表名称！");
            }
            else
            {
                foreach (DataRowView playListName in cbPlayList.Items)
                {
                    if (playListName["Name"].ToString() == newPlayListName)
                    {
                        MessageBox.Show("已存在相同的播放列表名称！");
                        return;
                    }
                }
                DialogResult dr = MessageBox.Show("确定增加这个播放列表吗？", "请确认", MessageBoxButtons.YesNo);
                if (dr == DialogResult.Yes)
                {
                    await sdh.RunCommandAsync(sqlInsertPlayList);
                    await GetPlayList();

                }
            }
        }
        /// <summary>
        /// 打开预览窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 细节调整ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvPlayList.SelectedRows.Count == 1)
            {
                int rowIndex = this.dgvPlayList.SelectedCells[0].RowIndex;
                DisplayElement displayElement = new DisplayElement();
                displayElement.Msg = this.dgvPlayList.Rows[rowIndex].Cells["显示内容"].Value.ToString();
                displayElement.MsgX = this.dgvPlayList.Rows[rowIndex].Cells["坐标X"].Value.ToString();
                displayElement.MsgY = this.dgvPlayList.Rows[rowIndex].Cells["坐标Y"].Value.ToString();
                displayElement.Delay = this.dgvPlayList.Rows[rowIndex].Cells["停留时间"].Value.ToString();
                displayElement.FontSize = this.dgvPlayList.Rows[rowIndex].Cells["字号"].Value.ToString();
                displayElement.Colour = this.dgvPlayList.Rows[rowIndex].Cells["字体颜色"].Value.ToString();
                using (FcmsPreviewForm previewForm = new FcmsPreviewForm(displayElement))
                {
                    previewForm.fontSizecomboBox.Text = displayElement.FontSize;
                    previewForm.colorcomboBox.Text = displayElement.Colour;
                    previewForm.showTypecomboBox.Text = "立即出现";
                    previewForm.fontcomboBox.Text = "宋体";
                    
                    if (previewForm.ShowDialog() == DialogResult.OK)
                    {
                        BeginEditGridValue();
                        this.dgvPlayList.CurrentCell = null;
                        this.dgvPlayList.Rows[rowIndex].Cells["显示内容"].Value = displayElement.Msg;
                        this.dgvPlayList.Rows[rowIndex].Cells["坐标X"].Value = displayElement.MsgX;
                        this.dgvPlayList.Rows[rowIndex].Cells["坐标Y"].Value = displayElement.MsgY;
                        //this.dgvPlayList.Rows[rowIndex].Cells[8].Value = element.Font;
                        this.dgvPlayList.Rows[rowIndex].Cells["字号"].Value = displayElement.FontSize;
                        this.dgvPlayList.Rows[rowIndex].Cells["字体颜色"].Value = displayElement.Colour;
                        //this.dgvPlayList.Rows[rowIndex].Cells[11].Value = element.ShowType;
                        EndEditGridValue();
                    }
                    return;
                }
            }
        }
        /// <summary>
        /// 向情报板内预置内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void preInstall_Click(object sender, EventArgs e)
        {
            try
            {
                savelog.Clear();

                if (dgvPlayList.RowCount == 0)
                {
                    MessageBox.Show("播放列表为空，请先添加情报板内容", "播放列表为空", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    FcmsPlayList fcmsPlayList = new FcmsPlayList();
                    List<byte> file = new List<byte>();
                    fcmsPlayList.ClearItem();
                    foreach (DataGridViewRow dgvr in dgvPlayList.Rows)
                    {
                        DisplayElement element = new DisplayElement();
                        element.Msg = dgvr.Cells["显示内容"].Value.ToString();
                        element.MsgX = dgvr.Cells["坐标X"].Value.ToString();
                        element.MsgY = dgvr.Cells["坐标Y"].Value.ToString();
                        element.Delay = (int.Parse(dgvr.Cells["停留时间"].Value.ToString()) * 100).ToString();
                        element.FontSize = dgvr.Cells["字号"].Value.ToString() + dgvr.Cells["字号"].Value.ToString();
                        element.Colour = dgvr.Cells["字体颜色"].Value.ToString();
                        savelog.Add(element.ToString());
                        fcmsPlayList.AddItem(element);
                    }
                    file = fcmsPlayList.GetPlayList();
                    bool successed = false;
                    preInstall.Enabled = false;
                    preInstall.Text = "请稍候";
                    using (StreamWriter writer = new StreamWriter(Application.StartupPath + @"\\play.lst", false, Encoding.Default))
                    {
                        await writer.WriteAsync(Encoding.Default.GetString(file.ToArray()));
                        
                        if (!selectFcmsParamName.Contains("COM"))
                        {
                            successed = fcmsProtocol.UploadFileBySql($"playlist\\{ cbInstallNo.Text }", file, fcmsId, selectFcmsParamName, controlSwitch);
                        }
                        if (selectFcmsParamName.Contains("COM"))
                        {
                            successed = fcmsProtocol.UploadFileBySp($"playlist\\{ cbInstallNo.Text }", file, fcmsId, selectFcmsParamName);
                        }
                    }
                    if (successed)
                    {
                        DBHelper sdh = new DBHelper();
                        string sql = $"UPDATE [R_FcmsStatus] SET [PlayListID]='{ playListId }' WHERE [FCMSID]='{ fcmsId }'";
                        string fcmstext = "";
                        foreach (var item in savelog)
                        {
                            fcmstext = fcmstext + " " + item;
                        }
                        string sql2 = $"insert into H_FCMSLog(FLogID,FCMSID,FCMSTEXT,UserID,UpdateTime) VALUES ('{ DBHelper.GetGuid }','{ fcmsId }','{ fcmstext }','{ Global.UserID }','{ DateTime.Now.ToString() }')";
                        await sdh.RunTransactionCommandsAsync(new string[] { sql, sql2 });
                        MessageBox.Show("指令下发成功");
                    }
                    preInstall.Text = "预置";
                    preInstall.Enabled = true;

                }

            }
            catch { }
        }

        private async void SelectFcmsAndPlaylist()
        {
            //取消两个ComboBox的事件绑定，防止修改其内容时触发事件
            cbFcmss.SelectedValueChanged -= cbFcmss_SelectedValueChanged;
            cbPlayList.SelectedValueChanged -= cbPlayList_SelectedValueChanged;
            await GetFcmss(); //获取情报板LIST
            await GetPlayList();//获取播放列表LIST
            cbFcmss.SelectedValueChanged += cbFcmss_SelectedValueChanged;
            cbPlayList.SelectedValueChanged += cbPlayList_SelectedValueChanged;

            foreach (DataRowView item in cbFcmss.Items)  //如果使用了情报板设备ID来打开窗体，则在此处将情报板的下拉选框选择为该ID
            {
                if (item["IDandPARAM"].ToString().Contains(deviceId))
                {
                    cbFcmss.SelectedValue = item["IDandPARAM"].ToString();
                }
            }
            
            cbFcmss_SelectedValueChanged(null, null);            
            //cbPlayList_SelectedValueChanged(null, null);            
            //FillTheGridView();//将播放列表内容填充至GRIDVIEW
        }

        private void FcmsForm_Load(object sender, EventArgs e)
        {
            SelectFcmsAndPlaylist();
        }
    }
}
